﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;

namespace BuienRadarAutohostedAppWeb
{
    /// <summary>
    /// Summary description for Buienradar
    /// </summary>
    public class Buienradar : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string buienradarUrl = "";
            String buienradarHTML = "";
            /*Register at http://www.microsoft.com/maps/ to get a key*/
            string BingMapKey = "AvL7zxxtdfoqL_o99O7qoes1H150Cq4Mlx0866aeoP92xP6b6_lfyJLI3PM7vh0P";
            string BingMapUrl = "http://dev.virtualearth.net/REST/v1/Locations?o=xml&countryRegion={0}&locality={1}&postalCode={2}&userIp=127.0.0.1&maxResults=1&key={3}";
            string url;
            string width = "256";
            string height = "256";
            string country = "nl";
            string city = "Eindhoven";
            string postalcode = "5653PX";


            decimal widthFrame = 226;
            decimal heightFrame = 226;
            decimal latitude;
            decimal longitude;
            XElement root = null;
            try
            {
                width = context.Request.QueryString["width"];
                height = context.Request.QueryString["height"];
                country = context.Request.QueryString["country"];
                city = context.Request.QueryString["city"];
                postalcode = context.Request.QueryString["postalcode"];
                widthFrame = decimal.Parse(width) - 30;
                heightFrame = decimal.Parse(height) - 30;

                if (city != "" && postalcode != "")
                {

                    url = String.Format(BingMapUrl, country, city, postalcode, BingMapKey);

                    try
                    {
                        root = XElement.Load(url);
                    }
                    catch (Exception)
                    {

                    }


                    XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
                    ns.AddNamespace("ns", "http://schemas.microsoft.com/search/local/ws/rest/v1");

                    CultureInfo ci = new CultureInfo("en-us");


                    if (root != null &&
                        decimal.TryParse(root.XPathSelectElement("//ns:Location/ns:Point/ns:Latitude", ns).Value, NumberStyles.AllowDecimalPoint, ci.NumberFormat, out latitude) &&
                       decimal.TryParse(root.XPathSelectElement("//ns:Location/ns:Point/ns:Longitude", ns).Value, NumberStyles.AllowDecimalPoint, ci.NumberFormat, out longitude))
                    {

                        buienradarUrl = String.Format("http://mijn.buienradar.nl/lokalebuienradar.aspx?voor=1&lat={0}&x=1&y=1&lng={1}&overname=2&zoom=8&naam=&size=2&map=1",
                                                latitude.ToString("0.000000", ci.NumberFormat), longitude.ToString("0.000000", ci.NumberFormat));
                    }
                    else
                    {
                        buienradarUrl = String.Format("http://www2.buienradar.nl/display.php?width={0}&height={1}&country={2}&maptype=2&opacity=75",
                                               width, height, country);
                    }
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(buienradarUrl);

                    req.Method = "GET";
                    HttpWebResponse responseBuienradar = (HttpWebResponse)req.GetResponse();
                    Stream dataStream = responseBuienradar.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);

                    buienradarHTML = reader.ReadToEnd();
                    reader.Close();
                    responseBuienradar.Close();
                    dataStream.Close();

                    buienradarHTML = buienradarHTML.Replace("http://maps.google.com/maps", "//maps.google.com/maps");
                    buienradarHTML = buienradarHTML.Replace(@"<LINK REL=""SHORTCUT ICON"" HREF=""http://www.buienradar.nl/favicon.ico"">", "");

                    context.Response.ContentType = responseBuienradar.ContentType;
                    context.Response.AddHeader("Content-Length", responseBuienradar.ContentLength.ToString());
                }
                else
                {
                    buienradarUrl = "http://gratisweerdata.buienradar.nl/buienradar.php?type=256x256";


                    buienradarHTML = String.Format( @"<html>
                                            <head>
                                            <title>Buienradar.nl</title>
                                            </head>
                                            <body bgcolor='#FFFFFF' link='#0000FF' vlink='#0000FF' alink='#0000FF' topmargin='0' leftmargin='0'>
                                            <a href='http://www.buienradar.nl' target='_blank'>
                                            <img border='0' src='http://gratisweerdata.buienradar.nl/radar.php?type=256x256' alt='Buienradar.nl' width='{0}' height='{1}'></a>
                                            </body>
                                            </html>", width.ToString(), height.ToString());

                }

                
                context.Response.Write(buienradarHTML);
                context.Response.End();
            }
            catch (Exception ex)
            {
                context.Response.Write("<html><body>Er ging iets mis: " + ex.Message + "</body></html>");
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}